package game.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import sdk.common.MySSLSocketFactory;

/**
 * 云片短信发送
 * 
 * @ClassName: YunPianUtil
 * @author admin
 * @date 2017年9月8日
 *
 */
public class YunPianUtil {
	private static Logger logger = LoggerFactory.getLogger(YunPianUtil.class);

	private static String apikey = "4f7cda5033c585cc743572911f2ac96b";
	// 单条发送接口
	private static String singleSendUrl = "https://sms.yunpian.com/v2/sms/single_send.json";

	/*
	 * @param apikey 成功注册后登录云片官网,进入后台可查看
	 * 
	 * @param text 需要使用已审核通过的模板或者默认模板
	 * 
	 * @param mobile 接收的手机号,仅支持单号码发送
	 * 
	 * @return json格式字符串
	 */
	private static String singleSend(String mobile, String text) {
		Map<String, String> params = new HashMap<String, String>();// 请求参数集合
		params.put("apikey", apikey);
		params.put("mobile", mobile);
		params.put("text", text);
		String res = sendPost(singleSendUrl, params);

		Object[] log = { mobile, text, res };
		logger.info("----云片短信发送结果：mobile = {} , text = {} , res = {}", log);
		return res;
	}

	/**
	 * 生成验证码 @Title: generateText @Description:
	 * 
	 * @param title
	 * @param random
	 * @return 参数 @return String 返回类型 @throws
	 */
	private static String generateText(String title, String random) {
		String text = "【" + title + "】您的验证码是" + random + "。有效期为10分钟，请尽快验证，如非本人操作，请忽略。";
		return text;
	}

	/*
	 * 返回长度为【strLength】的随机数，在前面补0
	 */
	private static String getFixLenthString(int strLength) {
		Random rm = new Random();
		// 获得随机数
		double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
		// 将获得的获得随机数转化为字符串
		String fixLenthString = String.valueOf(pross);
		// 返回固定的长度的随机数
		return fixLenthString.substring(1, strLength + 1);
	}

	/**
	 * 发送短信
	 * 
	 * @Title: sendSms
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param
	 *            mobile
	 * @param @param
	 *            title 目前备案标题只有这两个： 闽闽棋牌 智豆游戏
	 * @param @return
	 *            参数
	 * @return boolean 返回类型
	 * @throws {"code":0,"msg":"发送成功","count":1,"fee":0.05,"unit":"RMB","mobile":"18*****756","sid":17545017894}
	 */
	public static boolean sendSms(String mobile, String title, String randomTxt) {
		String text = generateText(title, randomTxt);
		String sendres = singleSend(mobile, text);
		JSONObject obj = JSON.parseObject(sendres);
		Integer code = obj.getInteger("code");
		if (0 == code) {
			return true;
		}
		return false;
	}

	private static String sendPost(String postUrl, Map<String, String> params) {
		try {
			URL obj = new URL(postUrl);
			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
			String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36";
			// 添加请求头
			con.setRequestMethod("POST");
			con.setRequestProperty("User-Agent", USER_AGENT);
			con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

			SSLSocketFactory ssf = MySSLSocketFactory.getInstance().getSSLSocketFactory();
			con.setSSLSocketFactory(ssf);
			con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			StringBuffer sb = new StringBuffer();
			for (String key : params.keySet()) {
				sb.append("&").append(key).append("=").append(URLEncoder.encode(params.get(key), "utf-8"));
			}
			String urlParameters = sb.toString().replaceFirst("&", "");

			// logger.info("urlParameters:{}", urlParameters);
			con.setDoInput(true);
			// 发送Post请求
			con.setDoOutput(true);
			DataOutputStream wr = new DataOutputStream(con.getOutputStream());
			wr.writeBytes(urlParameters);
			wr.flush();
			wr.close();

			// int responseCode = con.getResponseCode();
			InputStream is;
			if (con.getResponseCode() >= 400) {
				is = con.getErrorStream();
			} else {
				is = con.getInputStream();
			}

			BufferedReader in = new BufferedReader(new InputStreamReader(is));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
			// logger.info("msg={}", response.toString());
			return response.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage());
		}
		return "post err!";

	}

	public static void main(String[] args) {
		sendSms("13761559632", "闽闽棋牌牛牛牛", getFixLenthString(4));
	}

}
